<template>
  <div class="app-container">
    <el-row :gutter="20">
      <splitpanes :horizontal="this.$store.getters.device === 'mobile'" class="default-theme">
        <!--部门数据-->
        <pane size="16" v-if="false">
          <el-col>
            <div class="head-container">
              <el-input v-model="deptName" placeholder="请输入院区/科室" clearable size="small"
                        prefix-icon="el-icon-search" style="margin-bottom: 20px"/>
            </div>
            <div class="head-container">
              <el-tree :data="deptOptions" :props="defaultProps" :expand-on-click-node="false"
                       :filter-node-method="filterNode" ref="tree" node-key="id" default-expand-all highlight-current
                       @node-click="handleNodeClick"/>
            </div>
          </el-col>
        </pane>
        <!--用户数据-->
        <pane size="100">
          <el-col>
            <div ref="formRef">
              <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                       label-width="68px">
                <el-form-item label="医生" prop="doctorName">
                  <el-input
                    v-model="queryParams.doctorName"
                    placeholder="医生姓名"
                    clearable
                    style="width: 130px;"
                  />
                </el-form-item>
                <el-form-item label="患者" prop="patientName">
                  <el-input
                    v-model="queryParams.patientName"
                    placeholder="患者姓名"
                    clearable
                    style="width: 130px;"

                  />
                </el-form-item>
                <el-form-item label="画课日期">
                  <el-date-picker v-model="dateRange" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
                                  range-separator="-" start-placeholder="开始日期"
                                  end-placeholder="结束日期"></el-date-picker>
                </el-form-item>
                <el-form-item label="画课项目" prop="courseProject">
                  <el-select v-model="queryParams.courseProject" placeholder="画课项目" style="width: 130px;" clearable>
                    <el-option
                      v-for="dict in dict.type.sys_course_project"
                      :key="dict.label"
                      :label="dict.label"
                      :value="dict.label"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="画课时长" prop="courseHour">
                  <el-select v-model="queryParams.courseHour" placeholder="请选择时长" style="width: 130px;" clearable>
                    <el-option
                      v-for="dict in dict.type.sys_course_hour"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="画课状态" prop="courseStatus">
                  <el-select v-model="queryParams.courseStatus" placeholder="请选择" style="width: 130px;" clearable>
                    <el-option
                      v-for="item in courseStatusOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-form>
            </div>
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button
                  type="primary"
                  plain
                  icon="el-icon-edit"
                  size="mini"
                  :disabled="multiple"
                  @click="handleConfirmCourse"
                >批量画课
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="warning"
                  plain
                  icon="el-icon-download"
                  size="mini"
                  @click="handleExport"
                  v-hasPermi="['yushi:course:export']"
                >导出
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="danger"
                  plain
                  icon="el-icon-delete"
                  size="mini"
                  :disabled="multiple"
                  @click="handleDelete"
                  v-hasPermi="['yushi:patient:remove']"
                >删除
                </el-button>
              </el-col>
              <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
              <el-col :span="1.5" class="top-right-btn">
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
              </el-col>
              <el-col :span="1.5" class="top-right-btn">
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              </el-col>
            </el-row>

            <el-table v-loading="loading" :data="tableData" :height="tableHeight"
                      :summary-method="getSummaries"
                      show-summary
                      ref="summaryTable"
                      @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="60" align="center"/>
              <el-table-column label="序号" type="index" width="55" align="center">
                <template slot-scope="scope">
                  <span>{{ (pageNum - 1) * pageSize + scope.$index + 1 }}</span>
                </template>
              </el-table-column>
              <el-table-column label="医生姓名" align="center" prop="doctorName"/>
              <el-table-column label="患者姓名" align="center" prop="patientName"/>
              <el-table-column label="院区名称" align="center" prop="parentName" width="120">
                <template slot-scope="scope">
                  <span>{{ scope.row.dept.parentName }}</span>
                </template>
              </el-table-column>
              <el-table-column label="科室名称" align="center" prop="deptName" width="120">
                <template slot-scope="scope">
                  <span>{{ scope.row.dept.deptName }}</span>
                </template>
              </el-table-column>
              <el-table-column label="画课日期" align="center" prop="courseDate" width="180">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.courseDate, '{y}-{m}-{d}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="画课项目" align="center" prop="courseProject"/>
              <el-table-column label="画课时长" align="center" prop="courseHour">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.sys_course_hour" :value="scope.row.courseHour"/>
                </template>
              </el-table-column>
              <el-table-column label="画课状态" prop="courseStatus">
                <template v-slot="scope">
                  <span v-if="scope.row.courseStatus == 1" style="color: orange">待确认</span>
                  <span v-if="scope.row.courseStatus == 2" style="color: green">患者确认</span>
                  <span v-if="scope.row.courseStatus == 3" style="color: green">自动确认</span>
                </template>
              </el-table-column>
              <el-table-column label="确认时间" align="center" prop="confirmTime">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.confirmTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-edit"
                    @click="handleConfirmCourse(scope.row)"
                    v-if="scope.row.courseStatus == '1'"
                    v-hasPermi="['yushi:doctor:edit']"
                  >确认画课
                  </el-button>
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click="handleDelete(scope.row)"
                    v-hasPermi="['yushi:patient:remove']"
                  >删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <pagination
              v-show="total>0"
              :total="total"
              :page.sync="queryParams.pageNum"
              :limit.sync="queryParams.pageSize"
              @pagination="getList"
            />
          </el-col>
        </pane>
      </splitpanes>
    </el-row>
    <!-- 添加或修改画课记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="医生用户ID" prop="doctorId">
          <el-input v-model="form.doctorId" placeholder="请输入医生用户ID"/>
        </el-form-item>
        <el-form-item label="患者用户ID" prop="patientId">
          <el-input v-model="form.patientId" placeholder="请输入患者用户ID"/>
        </el-form-item>
        <el-form-item label="画课日期" prop="courseDate">
          <el-date-picker clearable
                          v-model="form.courseDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择画课日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="画课项目名称" prop="courseProject">
          <el-input v-model="form.courseProject" placeholder="请输入画课项目名称"/>
        </el-form-item>
        <el-form-item label="画课时长" prop="courseHour">
          <el-input v-model="form.courseHour" placeholder="请输入画课时长"/>
        </el-form-item>
        <el-form-item label="画课确认时间" prop="confirmTime">
          <el-date-picker clearable
                          v-model="form.confirmTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择画课确认时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="画课确认用户ID" prop="confirmBy">
          <el-input v-model="form.confirmBy" placeholder="请输入画课确认用户ID"/>
        </el-form-item>
        <el-form-item label="删除标志" prop="delFlag">
          <el-input v-model="form.delFlag" placeholder="请输入删除标志"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listCourse, getCourse, delCourse, addCourse, updateCourse, confirmCourse} from "@/api/yushi/course"
import {deptTreeSelect} from "@/api/system/user";
import Treeselect from "@riophae/vue-treeselect"
import "@riophae/vue-treeselect/dist/vue-treeselect.css"
import {Splitpanes, Pane} from "splitpanes"
import "splitpanes/dist/splitpanes.css"
import {parseTime} from "@/utils/ruoyi";
import {getEndDateFn} from "@/utils/dateUtils";

export default {
  name: "Course",
  components: {Treeselect, Splitpanes, Pane},
  dicts: ['sys_course_hour', 'sys_course_project'],
  data() {
    return {
      tableHeight: 400,//表格高度
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      pageNum: 1,
      pageSize: 10,
      // 日期范围
      dateRange: [],
      // 画课记录表格数据
      tableData: [],
      //画课确认状态
      courseStatusOptions: [
        {value: '', label: '全部'},
        {value: '1', label: '待确认'},
        {value: '2', label: '患者确认'}
      ],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 所有部门树选项
      deptOptions: undefined,
      // 过滤掉已禁用部门树选项
      enabledDeptOptions: undefined,
      // 查询参数
      queryParams: {
        orderByColumn: 'a.create_time',
        isAsc: 'desc',
        pageNum: 1,
        pageSize: 10,
        doctorName: null,
        patientName: null,
        doctorId: null,
        patientId: null,
        courseDate: null,
        courseProject: null,
        courseHour: null,
        courseStatus: null,
        confirmTime: null,
        confirmBy: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      beginTime: null, //查询开始日期
      endTime: null, //查询结束日期
      courseMonth: null, //课程所属月份
      resizeObserver: null
    }
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    const doctorName = this.$route.query && this.$route.query.doctorName
    const patientName = this.$route.query && this.$route.query.patientName
    const courseStatus = this.$route.query && this.$route.query.courseStatus
    this.beginTime = this.$route.query && this.$route.query.beginTime
    this.endTime = this.$route.query && this.$route.query.endTime
    this.courseMonth = this.$route.query && this.$route.query.courseMonth
    // 如果画课统计页面没有选择时间范围,则根据所属月份获取该月第一天和最后一天,如果是本月,则最后一天是今天
    if (this.courseMonth != null && (this.endTime == null || this.endTime == 'null') && (this.beginTime == null || this.beginTime == 'null')) {
      this.beginTime = this.courseMonth + '-01'
      this.endTime = getEndDateFn(this.courseMonth)
      if (Date.parse(this.endTime) > new Date()) {
        const now = new Date();
        const year = now.getFullYear();
        const month = (now.getMonth() + 1).toString().padStart(2, '0'); // 月份从0开始，需要加1，并确保是两位数
        const day = now.getDate().toString().padStart(2, '0'); // 确保日期是两位数
        const today = year + "-" + month + "-" + day;
        this.endTime = today
      }
      this.dateRange.push(this.beginTime)
      this.dateRange.push(this.endTime)
    }
    this.queryParams.doctorName = doctorName
    this.queryParams.patientName = patientName
    this.queryParams.courseStatus = courseStatus
    this.getList()
    this.getTableHeight()
  },
  mounted() {
    //挂载window.onresize事件(动态设置table高度)
    const _this = this;
    window.onresize = () => {
      if (_this.resizeFlag) {
        clearTimeout(_this.resizeFlag);
      }
      _this.resizeFlag = setTimeout(() => {
        _this.getTableHeight();
        _this.resizeFlag = null;
      }, 100);
    };
    this.initResizeObserver();
  },
  beforeDestroy() {
    if (this.resizeObserver) {
      this.resizeObserver.disconnect();
    }
  },
  methods: {
    // 初始化ResizeObserver
    initResizeObserver() {
      if (typeof ResizeObserver !== 'undefined' && this.$refs.tableWrapper) {
        this.resizeObserver = new ResizeObserver(() => {
          this.updateTableLayout();
        });
        this.resizeObserver.observe(this.$refs.tableWrapper);
      }
    },

    // 更新表格布局
    updateTableLayout() {
      if (this.$refs.summaryTable && this.$refs.summaryTable.doLayout) {
        setTimeout(() => {
          this.$refs.summaryTable.doLayout();
        }, 100);
      }
    },

    //计算table高度(动态设置table高度)
    getTableHeight() {
      const innerHeight = window.innerHeight
      const formRefHeight = this.$refs.formRef.offsetHeight
      //距离页面下方的高度
      let tableH = 218 + formRefHeight;
      let tableHeightDetil = innerHeight - tableH;
      if (tableHeightDetil <= 300) {
        this.tableHeight = 300;
      } else {
        this.tableHeight = window.innerHeight - tableH;
      }
      this.$nextTick(() => {
        this.updateTableLayout();
      });
    },

    /** 查询画课记录列表 */
    getList() {
      this.loading = true
      listCourse(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.tableData = response.rows
        this.total = response.total
        this.loading = false
        // this.getDeptTree()
        this.getTableHeight()
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm("queryForm")
      this.queryParams = {
        orderByColumn: 'a.create_time',
        isAsc: 'desc',
        pageNum: 1,
        pageSize: 10,
        doctorId: null,
        patientId: null,
        courseDate: null,
        courseProject: null,
        courseHour: null,
        courseStatus: null,
        confirmTime: null,
        confirmBy: null,
      }
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.courseId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加画课记录"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const courseId = row.courseId || this.ids
      getCourse(courseId).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改画课记录"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.courseId != null) {
            updateCourse(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addCourse(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 确认画课 */
    handleConfirmCourse(row) {
      const courseIds = row.courseId || this.ids
      let counts = courseIds.length
      if (courseIds.length == 0 || courseIds.length == undefined) {
        counts = 1
      }
      this.$modal.confirm('是否确认画课"' + counts + '"条数据项？').then(function () {
        return confirmCourse(courseIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("确认画课成功")
      }).catch(() => {
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const courseIds = row.courseId || this.ids
      let content = '是否确认删除画课记录编号为"' + courseIds + '"的数据项？';
      if (this.ids.length > 0) {
        content = '是否确认删除"' + this.ids.length + '"条参数数据？';
      } else {
        content = '是否确认删除 1 条参数数据？';
      }
      this.$modal.confirm(content).then(function () {
        return delCourse(courseIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('/yushi/course/export', {
        ...this.queryParams
      }, `画课记录_${parseTime(new Date(), '{y}{m}{d}{h}{i}{s}')}.xlsx`)
    },
    // 合计行计算方法
    getSummaries(param) {
      const {columns, data} = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }

        const prop = column.property;
        if (prop === 'courseHour') {
          const values = data.map(item => {
            if (prop === 'total') {
              return item.amount * item.quantity;
            }
            return Number(item[prop]);
          });

          if (!values.every(value => isNaN(value))) {
            const sum = values.reduce((prev, curr) => {
              const value = Number(curr);
              return !isNaN(value) ? prev + value : prev;
            }, 0);

            if (prop === 'amount' || prop === 'total') {
              sums[index] = '¥ ' + sum.toLocaleString();
            } else {
              sums[index] = sum.toLocaleString();
            }
          } else {
            sums[index] = 'N/A';
          }
        } else {
          sums[index] = '';
        }
      });

      return sums;
    },

    // 过滤禁用的部门
    filterDisabledDept(deptList) {
      return deptList.filter(dept => {
        if (dept.disabled) {
          return false
        }
        if (dept.children && dept.children.length) {
          dept.children = this.filterDisabledDept(dept.children)
        }
        return true
      })
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id
      this.handleQuery()
    },
  }
}
</script>
